package pixeleditor.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;

import common.gui.IViewable;
import common.i18n.ChangeLanguage;
import common.i18n.IChangeLanguage;
import common.util.FileHandler;

import pixeleditor.ctrl.ControlFactory;

@SuppressWarnings("serial")
public class ChooseBackgroundDialog extends JDialog implements IChangeLanguage, IViewable {

	private JList list = new JList();
	private JScrollPane sp = new JScrollPane(list);
	private JLabel bg = new JLabel();
	private JButton fi = new JButton("klar");

	public ChooseBackgroundDialog() {
		ChangeLanguage.addObserver(this);
		initControls();
		initComponents();

	}

	private void initComponents() {

		setTitle("Background");

		bg.setBackground(Color.WHITE);
		bg.setOpaque(true);
		bg.setVisible(true);
		bg.setPreferredSize(new Dimension(400, 400));
		sp.setPreferredSize(new Dimension(200, 400));
		String f = File.separator;
		//Load the different background that can be chosen
		list.setListData(FileHandler.loadResources(
				"." + f + 
				"resource" + f +
				"images" + f + 
				"backgrounds", ".png").toArray());

		setSize(new Dimension(610,400));

		add(bg, BorderLayout.WEST);
		add(sp, BorderLayout.EAST);
		add(fi, BorderLayout.SOUTH);

		setVisible(true);
		setResizable(false);
		setModal(true);


	}

	private void initControls() {
		ControlFactory.getControl(ControlFactory.CHOOSE_BACKGROUND_DIALOG_CTRL).addView(this);
		MouseListener ml = (MouseListener) ControlFactory.getControl(ControlFactory.CHOOSE_BACKGROUND_DIALOG_CTRL);
		list.addMouseListener(ml);

		ActionListener a = (ActionListener) ControlFactory.getControl(ControlFactory.CHOOSE_BACKGROUND_DIALOG_CTRL);
		fi.addActionListener(a);
	}

	@Override
	public void setLanguage(ResourceBundle rb) {
		setTitle(rb.getString("editorBackground"));

	}

	@Override
	public void updateView(Object o) {
		if(o.equals("dispose"))
			this.setVisible(false);
		else {
			try {
				BufferedImage bi = FileHandler.getImage("backgrounds", (String)o + ".png");
				bg.setIcon(new ImageIcon(bi.getScaledInstance(400,400,0)));		
			} catch (IOException e) {
				System.out.println("Can't find image: " + e.getLocalizedMessage());
			}
		}

	}

}
